<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery" v-perm="'department:list'">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!--
      :data="departments" - 绑定的数据[]
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框/忙等框
      @selection-change="selsChange" - 选项改变
      批量删除：type="selection - 选项
    -->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="120" >
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120" :formatter="formatSex" >
			</el-table-column>
			<el-table-column prop="dirPath" label="上级" width="120" >
			</el-table-column>
			<el-table-column prop="state" label="状态" width="120">
          <template slot-scope="scope">
            <span style="color: green" v-if="scope.row.state==1">正常</span>
            <span style="color: red" v-else-if="scope.row.state==0">停用</span>
            <span style="color: darkslategray" v-else>未知</span>
          </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="经理" width="80" >
			</el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="80" >
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-perm="'department:save'">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'department:patch'">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :current-page="currentPage" :total="totals" style="float:right;">
      </el-pagination>
		</el-col>

    <!--添加和修改的对话框-->
    <!--
      :close-on-click-modal="false" - 点击对话外面的区域不关闭对话框
      :model="saveForm" - 绑定表单数据
      :rules="saveFormRules" - 校验规则
      ref="saveForm" - 对话框的名称 - 验证的时候需要用
      auto-complete="off" - 自动完成
    -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">
          <el-select v-model="saveForm.manager_id" placeholder="请选择" clearable>
            <!--
              el-select - 下拉框
                v-model="saveForm.manager" - 回显数据
                placeholder="请选择" - 提示语
                el-option - 每一个选项
                v-for="item in managers" - 遍历
                :label="item.username" - 回显哪一个值：item对象的username属性
                :value="item" - 点击保存你要传递到后端的数据
              回显机制：
                v-model="saveForm.manager"  与 v-for中的对应
                  对应的是整个对象【id】
                :label="item.username" - 回显的时候显示哪一个：item对象的username属性
                value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
                value-key="id" - 因为我们绑定的是一个对象saveForm.manager，
                  对象里面有多个值： id: 324, username: "东邪"
                使用id作为回显的唯一标识
            -->
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="上级部门">
          <!--
            el-cascader - 级联框
             :options="deptTree" - 级联框中要显示的数据 - List集合【部门树 - 菜单树】
             clearable 可清理的
             :props="{ checkStrictly: true, label: 'name',value:'id'}"
              label: 'name' - 显示那个属性的内容
              value:'id'
            回显机制：
              v-model="parent"  与 :options="deptTree"对象对应
                对应的依据：
            deptTree
              每一个部门对象 - 都有dirPath
              dirPath = /2/7/18/23
          -->
            <el-cascader v-model="saveForm.parent"
                :options="deptTree"
                :props="{ checkStrictly: true, label:'name',value:'id'}"
                clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>
	export default {
		data() {
			return {
			  //分页相关数据
        departments: [],
        totals:0,
        pageSize:5,
        currentPage:1,
        listLoading: false,


        //高级查询所需数据
        keyword: '',//关键字查询


        //模型数据data,多条数据选中,用于删除
				sels: [],//列表选中列

				saveFormVisible: false, //对话框是否显示：默认不显示
				saveLoading: false,     //对话框中的加载框/忙等框
        title:'',               //标题
				saveFormRules: {        //校验规则
					sn: [
            //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入部门的编号
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					],
          name: [
            //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入部门的名称
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				saveForm: {
          id: null,
					sn: '',
					name: '',
					state: 1,
          manager_id: null,
          parent_id: null,
          managers:null,
          parent:null

				},
        //部门经理
        managers:[],
        //部门树 - 无限级数
        deptTree:[]
			}
		},
		methods: {
      //1.分页查询：获取部门列表
      getDepartments() {
        let para = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword:this.keyword
        };
        this.listLoading = true;

        this.$http.post("/department",para).then((res) => {
          this.totals = res.data.totals;
          this.departments = res.data.data;
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error('系统繁忙，请稍后重试!!!');
        });
      },


      //2.点击某一页触发的方法
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getDepartments();
      },


      //3.关键字查询
      keywordQuery(){
        this.currentPage = 1;
        this.getDepartments();
      },


      //4.删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '温馨提示', {
          type: 'warning'
        }).then(() => { //点击确认之后要执行的代码
          //显示加载框
          this.listLoading = true;
          //获取id
          var id= row.id;
          this.$http.delete("/department/"+id).then(res=>{
            if (res.data.success){ //删除成功
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              this.$message.success("删除成功") //3s自动消失
              this.getDepartments();
            }else {
              this.$message.error('系统繁忙，请稍后重试【500】');
            }
            this.listLoading = false;//关闭加载框
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => { //点击取消之后要执行的代码
        });
      },


      //5.选项改变触发此方法
      selsChange: function (sels) {
        //获取被选中的对象  - 集合
        this.sels = sels;
      },


      //6.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.patch("/department",ids).then(res=>{
            if (res.data.success){ //删除成功
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              this.$message.success("删除成功") //3s自动消失
              this.getDepartments();
            }else {
              this.$message.error('系统繁忙，请稍后重试【500】');
            }
            this.listLoading = false;//关闭加载框
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => {
        });
      },


      //7.点击添加按钮弹出对话框,增加功能要重置
      handleAdd: function () {
        this.saveForm = {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null,
          managers:null,
          parent:null
        };
        this.title = " 添 加 "
        //获取部门经理们
        this.getManagers();
        //获取部门树
        this.getDeptTree();
        //显示对话框
        this.saveFormVisible = true;
      },


      //8.点击修改按钮弹出对话框
      handleEdit: function (index, row) {
        //克隆：防止对象引用修改显示的数据
        this.saveForm = Object.assign({}, row);
        this.title = " 修 改 ";
        //获取部门经理们
        this.getManagers();
        //获取部门树
        this.getDeptTree();

        //对上级部门回显的处理:{} - []
        var dirPath = this.saveForm.dirPath; //   /2/7/18/23 - [2,7,18]
        var arr = dirPath.split("/");  //["","2","7","18","23"]
        var resultArr = [];
        for(var i=1;i<arr.length-1;i++){
          resultArr[i-1] = parseInt(arr[i]); //将字符串转成整数
          //第一次：resultArr[0] = arr[1] = "2";
          //第二次：resultArr[1] = arr[2] = 7
        }
        this.saveForm.parent = resultArr;
        // console.log(this.saveForm.parent)

        //显示对话框
        this.saveFormVisible = true;
      },


      //9.点击提交按钮添加或修改数据
      saveSubmit: function () {
          this.$refs.saveForm.validate((valid) => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.saveLoading = true;
                let para = Object.assign({}, this.saveForm);

                //提交数据时上级部门数据格式做处理：[2,7,17]
                //对父部门做处理
                var parentTmp = para.parent;// [2,7,17]  17是父部门
                //null不重要  - 对象是可以赋值为null
                if (parentTmp){
                  para.parent = null;//为了避免400 - 后端是用对象接收，前端修改之后是[]
                  //后端使用下面这个parent_id，不用parent对象
                  para.parent_id = parentTmp[parentTmp.length-1];
                  // console.log(para.parent_id)
                }

                this.$http.put("/department",para).then(res=>{
                  if (res.data.success){
                    this.$message.success("操作成功！")
                    this.getDepartments()
                  }else {
                    this.$message.error("系统繁忙，请稍后重试。【500】")
                  }
                  this.saveLoading=false;//不显示加载框
                  this.saveFormVisible=false;//不显示对话框
                }).catch(res=>{
                  this.$message.error("系统繁忙，请稍后重试。【400】,【404】")
                })
              });
            }
          });
        },


      //10.getManagers
      getManagers(){
        this.$http.get("/employee").then(res=>{
          this.managers=res.data;
        })
      },


      //11.deptTree
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res=>{
          this.deptTree=res.data;
        })
      },


		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>